﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Windows.Forms;
using EO;
using DAO;
using LoginSqlServer.LIB;

namespace LoginSqlServer
{
    public partial class frmMain : Form
    {
        List<ColumnEO> columnName = new List<ColumnEO>();
        List<String> tableName = new List<String>();
        TableEO objTbl = new TableEO();

        String userpass;

        public frmMain()
        {
            InitializeComponent();
        }

        private void cmbAuthentication_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbAuthentication.SelectedIndex == 0)
            {
                txtUsername.Enabled = false;
                txtPassword.Enabled = false;
            }
            else
            {
                txtUsername.Enabled = true;
                txtPassword.Enabled = true;
            }
        }

        private void btnConnectDB_Click(object sender, EventArgs e)
        {
            //Quyền Windows
            #region Windows Authentication
            if (cmbAuthentication.SelectedIndex == 0)
            {
                userpass = "";
                cmbDatabase.Items.Clear();
                var con = new SqlConnection("Data Source=" + txtServer.Text + ";Initial Catalog=master;Integrated Security=True;" + userpass);
                var cmd = new SqlCommand("SP_DATABASES", con);
                SqlDataReader reader;
                try
                {
                    con.Open();
                    reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        cmbDatabase.Items.Add(reader[0].ToString());
                    }
                    cmbDatabase.Enabled = true;
                    cmbDatabase.SelectedIndex = 0;
                    lblMsg.Text = "Connected!";
                    lblMsg.ForeColor = System.Drawing.Color.Blue;
                }
                catch
                {
                    MessageBox.Show("Lỗi, vui lòng thử lại!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (con.State == ConnectionState.Open)
                        con.Close();
                    con.Dispose();
                    cmd.Dispose();
                }
            }
            #endregion
            //Quyền SQL Server
            #region Sql Server Authentication


            else if (cmbAuthentication.SelectedIndex == 1)
            {
                userpass = "User Id=" + txtUsername.Text + ";Password=" + txtPassword.Text + ";";
                cmbDatabase.Items.Clear();
                var con = new SqlConnection("Data Source=" + txtServer.Text + ";Initial Catalog=master;" + userpass);
                var cmd = new SqlCommand("SP_DATABASES", con);
                SqlDataReader reader;
                try
                {
                    con.Open();
                    reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        cmbDatabase.Items.Add(reader[0].ToString());
                    }
                    cmbDatabase.Enabled = true;
                    cmbDatabase.SelectedIndex = 0;
                    lblMsg.Text = "Connected!";
                    lblMsg.ForeColor = System.Drawing.Color.Blue;
                }
                catch
                {
                    MessageBox.Show("Lỗi, vui lòng thử lại!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (con.State == ConnectionState.Open)
                        con.Close();
                    con.Dispose();
                    cmd.Dispose();
                }
            }
            #endregion
        }

        private void cmbDatabase_SelectedIndexChanged(object sender, EventArgs e)
        {
            lstbField.Items.Clear();
            tableName = new List<string>();
            LibCommon.DatabaseName = cmbDatabase.Text;
            string Query =
                           @"SELECT [TABLE_NAME]
                           FROM INFORMATION_SCHEMA.TABLES
                           WHERE table_type = 'BASE TABLE' AND TABLE_NAME <> 'sysdiagrams'";
            var con = new SqlConnection("Data Source=" + txtServer.Text + ";Initial Catalog=" + cmbDatabase.Text + ";" + userpass);
            var cmd = new SqlCommand(Query, con);
            SqlDataReader reader;
            try
            {
                con.Open();
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    lstbField.Items.Add(reader[0].ToString());
                    tableName.Add(reader[0].ToString());
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (con.State == ConnectionState.Open)
                    con.Close();
                con.Dispose();
                cmd.Dispose();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            txtProjectName.Text = Constants.Information.ProjectName;
            txtAuthor.Text = Constants.Information.Author;
            txtServer.Text = Constants.Information.ServerName;
            txtUsername.Text = Constants.Information.UserName;
            txtPassword.Text = Constants.Information.Password;
            cmbDatabase.SelectedValue = Constants.Information.DatabaseName;
            cmbAuthentication.SelectedIndex = 0;
            lblMsg.Text = "";
        }

        private void lstbField_SelectedIndexChanged(object sender, EventArgs e)
        {
            getColumn(lstbField.SelectedItem.ToString());
        }

        private void getColumn(string tbl)
        {
            columnName.Clear();
            string Query =
                            "SELECT" +
                            " col.COLUMN_NAME AS sColumnName" +
                            ", ISNULL(extp.value,'') AS sDescription" +
                            ", '' AS sDataTypeCSharp" +
                            ", UPPER(col.DATA_TYPE) AS sSQL_DataType" +
                            ", ISNULL(col.CHARACTER_MAXIMUM_LENGTH,0) AS sSQL_DataLength" +
                            ", 0 AS iTypeControl" +
                            ", 0 AS bPrimaryKey" +
                            ", 0 AS bForeignKey" +
                            ", CASE WHEN col.IS_NULLABLE = 'YES' THEN 1 ELSE 0 END AS bAllowNulls" +
                            ", COLUMNPROPERTY(OBJECT_ID('" + tbl + "'),col.COLUMN_NAME,'IsIdentity') AS bIdentity" +
                            ", 0 AS bTableAttack" +
                            " FROM INFORMATION_SCHEMA.Columns col LEFT OUTER JOIN sys.extended_properties extp" +
                            " ON extp.major_id = OBJECT_ID(col.TABLE_SCHEMA+'.'+col.TABLE_NAME) AND extp.minor_id = col.ORDINAL_POSITION AND extp.name = 'MS_Description'" +
                            " WHERE OBJECTPROPERTY(OBJECT_ID(col.TABLE_SCHEMA+'.'+col.TABLE_NAME), 'IsMsShipped')=0 AND col.Table_Name='" + tbl + "'";

            //                           @"SELECT i_s.[Column_NAME],i_s.[Data_Type],i_s.[CHARACTER_MAXIMUM_LENGTH], i_s.[IS_NULLABLE],s.value
            //                            FROM INFORMATION_SCHEMA.Columns i_s LEFT OUTER JOIN
            //                            sys.extended_properties s
            //                            ON
            //                            s.major_id = OBJECT_ID(i_s.TABLE_SCHEMA+'.'+i_s.TABLE_NAME)
            //                            AND s.minor_id = i_s.ORDINAL_POSITION
            //                            AND s.name = 'MS_Description'
            //                            WHERE OBJECTPROPERTY(OBJECT_ID(i_s.TABLE_SCHEMA+'.'+i_s.TABLE_NAME), 'IsMsShipped')=0 AND i_s.Table_Name='" + tbl + "'";
            var con = new SqlConnection("Data Source=" + txtServer.Text + ";Initial Catalog=" + cmbDatabase.Text + ";" + userpass);
            var cmd = new SqlCommand(Query, con);
            try
            {
                using (DataSet ds = new DataSet())
                {
                    using (SqlDataAdapter da = new SqlDataAdapter())
                    {
                        con.Open();
                        da.SelectCommand = cmd;
                        da.Fill(ds);
                        if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                        {
                            objTbl = ConvertNew.getFull_Info_Column(ds.Tables[0]);
                        }
                    }
                }
                columnName = objTbl.lstColumn;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "Lỗi: " + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                cmd.Connection.Close();
                cmd.Dispose();
            }



//            SqlDataReader reader;
//            try
//            {
//                con.Open();
//                reader = cmd.ExecuteReader();
//                while (reader.Read())
//                {
//                    #region Kiem tra IsIdentity
//                    string sql = @"Select [Column_NAME]
//                                   FROM INFORMATION_SCHEMA.Columns
//                                   WHERE Table_Name='" + tbl + "' AND COLUMNPROPERTY(OBJECT_ID('" + tbl + "'),'" + reader[0] + "','IsIdentity')=1";
//                    bool kt = false;
//                    var con2 = new SqlConnection("Data Source=" + txtServer.Text + ";Initial Catalog=" + cmbDatabase.Text + ";" + userpass);
//                    var command = new SqlCommand(sql, con2);
//                    try
//                    {
//                        con2.Open();
//                        kt = command.ExecuteScalar() != null;
//                    }
//                    catch (Exception)
//                    {
//                        kt = false;
//                    }
//                    finally
//                    {
//                        if (con2.State == ConnectionState.Open)
//                            con2.Close();
//                        con2.Dispose();
//                        command.Dispose();
//                    }
//                    #endregion

//                    #region Kiem tra IsPrimaryKey
//                    //SELECT column_name
//                    //FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
//                    //WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
//                    //AND table_name = 'tblDiemThi'

//                    string queryPK = @"select constraint_name from Information_schema.CONSTRAINT_COLUMN_USAGE
//                                     where OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1 AND table_name='" + tbl + "' and column_name='" + reader[0].ToString() + "'";
//                    bool checkPK = false;
//                    var conPK = new SqlConnection("Data Source=" + txtServer.Text + ";Initial Catalog=" + cmbDatabase.Text + ";" + userpass);
//                    SqlCommand commandPK = null;
//                    try
//                    {
//                        conPK.Open();
//                        commandPK = new SqlCommand(queryPK, conPK);
//                        if (commandPK.ExecuteScalar() != null)
//                        {
//                            string s = commandPK.ExecuteScalar().ToString();
//                            if (s != "")
//                                checkPK = true;
//                        }
//                    }
//                    catch (Exception)
//                    {
//                        checkPK = false;
//                    }
//                    finally
//                    {
//                        if (conPK.State == ConnectionState.Open)
//                            conPK.Close();
//                        conPK.Dispose();
//                        commandPK.Dispose();
//                    }
//                    #endregion

//                    #region Kiem tra IsForeignKey

//                    string queryFK = @"select constraint_name from Information_schema.CONSTRAINT_COLUMN_USAGE
//                                     where OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsForeignKey') = 1  and table_name='" + tbl + "' and column_name='" + reader[0].ToString() + "'";
//                    bool checkFK = false;
//                    var conFK = new SqlConnection("Data Source=" + txtServer.Text + ";Initial Catalog=" + cmbDatabase.Text + ";" + userpass);
//                    SqlCommand commandFK = null;
//                    try
//                    {
//                        conFK.Open();
//                        commandFK = new SqlCommand(queryFK, conFK);
//                        if (commandFK.ExecuteScalar() != null)
//                        {
//                            string s = commandFK.ExecuteScalar().ToString();
//                            if (s != "")
//                                checkFK = true;
//                        }
//                    }
//                    catch (Exception)
//                    {
//                        checkFK = false;
//                    }
//                    finally
//                    {
//                        if (conFK.State == ConnectionState.Open)
//                            conFK.Close();
//                        conFK.Dispose();
//                        commandFK.Dispose();
//                    }
//                    #endregion

//                    var cl = new ColumnEO
//                    {
//                        sColumnName = reader[0].ToString(),
//                        sDataTypeSQL = reader[1].ToString(),
//                        bIdentity = kt,
//                        sDataTypeSQLLength = reader[2].ToString(),
//                        bPrimaryKey = checkPK,
//                        bForeignKey = checkFK,
//                        bAllowNulls = ((reader[3].ToString().ToUpper() == "YES") ? true : false),
//                        sDescription = reader[4].ToString()
//                    };

//                    columnName.Add(cl);
//                }
//                reader.Close();
//            }
//            catch (SqlException ex)
//            {
//                MessageBox.Show(ex.Message, "Lỗi: " + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
//            }
//            finally
//            {
//                if (con.State == ConnectionState.Open)
//                    con.Close();
//                con.Dispose();
//                cmd.Dispose();
//            }
        }
        private void btnDAO_Click(object sender, EventArgs e)
        {
            lblMsg.Text = "";
            try
            {
                String tblName = LoadConfig();
                if (!String.IsNullOrEmpty(tblName))
                {
                    LibCommon.fncDataAccessObject(columnName, tblName);
                    lblMsg.Text = "Generate code success!";
                    lblMsg.ForeColor = System.Drawing.Color.Blue;
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = ex.Message;
                lblMsg.ForeColor = System.Drawing.Color.Red;
            }
            //try
            //{
            //    if (lstbField.Items.Count > 0 && lstbField.SelectedIndex != -1)
            //    {
            //        var f = new frmDataAccessObject(columnName, lstbField.SelectedItem.ToString());
            //        f.ShowDialog();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message, "Lỗi: "+ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
        }

        private void btnAspx_Click(object sender, EventArgs e)
        {
            lblMsg.Text = "";
            try
            {
                if (lstbField.Items.Count > 0 && lstbField.SelectedIndex != -1)
                {
                    string tblName = lstbField.SelectedItem.ToString();
                    if (tblName.PadRight(3, ' ').Contains("tbl"))
                    {
                        tblName = tblName.Substring(3);
                    }
                    LibCommon.DataAccessObjectEx = " _" + tblName + "DAO";
                    LibCommon.DataAccessObject = " " + tblName + "DAO";
                    LibCommon._EntityObject = " _" + tblName + "EO";
                    LibCommon.EntityObject = " " + tblName + "EO";
                    LibCommon.objEntityObject = " obj" + tblName + "EO";
                    LibCommon.UI = tblName + "UI";
                    LibCommon._DetailUC = tblName + "_DetailUC";
                    LibCommon._DetailUC1 = tblName + "_DetailUC1";
                    LibCommon._ListUC = tblName + "_ListUC";
                    LibCommon._ListUC1 = tblName + "_ListUC1";
                    LibCommon._NewUC = tblName + "_NewUC";

                    LibCommon.fncAspx(columnName, tblName);
                    LibCommon.fncAspxCs(columnName, tblName);
                    LibCommon.fncAspxDesignerCs(columnName, tblName);
                }
                lblMsg.Text = "Generate code success!";
                lblMsg.ForeColor = System.Drawing.Color.Blue;
            }
            catch (Exception ex)
            {
                lblMsg.Text = ex.Message;
                lblMsg.ForeColor = System.Drawing.Color.Red;
            }

            //try
            //{
            //    if (lstbField.Items.Count > 0 && lstbField.SelectedIndex != -1)
            //    {
            //        var f = new frmAspx(columnName, lstbField.SelectedItem.ToString());
            //        f.ShowDialog();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message, "Lỗi: " + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
        }

        private void btnCsharp_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    if (lstbField.Items.Count > 0 && lstbField.SelectedIndex != -1)
            //    {
            //        var f = new frmAspxCs(columnName, lstbField.SelectedItem.ToString());
            //        f.ShowDialog();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message, "Lỗi: " + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
        }

        private void btnProc_Click(object sender, EventArgs e)
        {
            lblMsg.Text = "";
            try
            {
                String tblName = LoadConfig();
                if (!String.IsNullOrEmpty(tblName))
                {
                    LibCommon.fncStoreProcedure(columnName, tblName);
                    lblMsg.Text = "Generate code success!";
                    lblMsg.ForeColor = System.Drawing.Color.Blue;
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = ex.ToString();
                lblMsg.ForeColor = System.Drawing.Color.Red;
            }
            //try
            //{
            //    if (lstbField.Items.Count > 0 && lstbField.SelectedIndex != -1)
            //    {
            //        var c = new frmStoreProcedure(columnName, lstbField.SelectedItem.ToString());
            //        c.ShowDialog();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message, "Lỗi: " + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
        }

        private void btnEO_Click(object sender, EventArgs e)
        {
            lblMsg.Text = "";
            try
            {
                if (lstbField.Items.Count > 0 && lstbField.SelectedIndex != -1)
                {
                    string tblName = lstbField.SelectedItem.ToString();
                    if (tblName.PadRight(3, ' ').Contains("tbl"))
                    {
                        tblName = tblName.Substring(3);
                    }
                    LibCommon.DataAccessObjectEx = " _" + tblName + "DAO";
                    LibCommon.DataAccessObject = " " + tblName + "DAO";
                    LibCommon._EntityObject = " _" + tblName + "EO";
                    LibCommon.EntityObject = " " + tblName + "EO";
                    LibCommon.objEntityObject = " obj" + tblName + "EO";
                    LibCommon.UI = tblName + "UI";
                    LibCommon._DetailUC = tblName + "_DetailUC";
                    LibCommon._DetailUC1 = tblName + "_DetailUC1";
                    LibCommon._ListUC = tblName + "_ListUC";
                    LibCommon._ListUC1 = tblName + "_ListUC1";
                    LibCommon._NewUC = tblName + "_NewUC";
                    LibCommon.isAddOK = false;

                    LibCommon.fncEntityObject(columnName, tblName);
                }
                lblMsg.Text = "Generate code success!";
                lblMsg.ForeColor = System.Drawing.Color.Blue;
            }
            catch (Exception ex)
            {
                lblMsg.Text = ex.Message;
                lblMsg.ForeColor = System.Drawing.Color.Red;
            }
            //try
            //{
            //    if (lstbField.Items.Count > 0 && lstbField.SelectedIndex != -1)
            //    {
            //        var c = new frmEntityObject(columnName, lstbField.SelectedItem.ToString());
            //        c.ShowDialog();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message, "Lỗi: " + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
        }

        private void btnDesigner_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    if (lstbField.Items.Count > 0 && lstbField.SelectedIndex != -1)
            //    {
            //        var f = new frmAspxDesignerCs(columnName, lstbField.SelectedItem.ToString());
            //        f.ShowDialog();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message, "Lỗi: " + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
        }

        private static string getPath(string strFolder, bool bType)
        {
            String root = Application.StartupPath.ToString() + "\\";
            if (bType)
                strFolder = root + Constants.Information.Author + "\\" + strFolder;
            else
                strFolder = root + Constants.FolderTemp.Template + "\\" + strFolder;
            return strFolder;
        }

        private void btnCopyLibrary_Click(object sender, EventArgs e)
        {
            CopyLib();
        }

        private void CopyLib()
        {
            lblMsg.Text = "";
            try
            {
                String root = Application.StartupPath.ToString() + "\\";

                #region "Kiểm tra tồn tại và tạo thư mục"
                //if (!Directory.Exists(getPath(LibCommon.Constants.FolderTemp.SharedLibraries, true)))
                //{
                //    System.IO.Directory.CreateDirectory(getPath(LibCommon.Constants.FolderTemp.SharedLibraries, true));
                //}
                //if (!Directory.Exists(getPath(LibCommon.Constants.FolderTemp.DataAccessObject, true)))
                //{
                //    System.IO.Directory.CreateDirectory(getPath(LibCommon.Constants.FolderTemp.DataAccessObject, true));
                //}
                if (!Directory.Exists(getPath(Constants.FolderTemp.App_Themes, true)))
                {
                    System.IO.Directory.CreateDirectory(getPath(Constants.FolderTemp.App_Themes, true));
                }

                if (!Directory.Exists(getPath(Constants.FolderTemp.Fonts, true)))
                {
                    System.IO.Directory.CreateDirectory(getPath(Constants.FolderTemp.Fonts, true));
                }
                if (!Directory.Exists(getPath(Constants.FolderTemp.DLL, true)))
                {
                    System.IO.Directory.CreateDirectory(getPath(Constants.FolderTemp.DLL, true));
                }
                if (!Directory.Exists(getPath(Constants.FolderTemp.PublicInterface, true)))
                {
                    System.IO.Directory.CreateDirectory(getPath(Constants.FolderTemp.PublicInterface, true));
                }
                if (!Directory.Exists(getPath(Constants.FolderTemp.Scripts, true)))
                {
                    System.IO.Directory.CreateDirectory(getPath(Constants.FolderTemp.Scripts, true));
                }
                //if (!Directory.Exists(getPath(LibCommon.Constants.FolderTemp.EntityObject, true)))
                //{
                //    System.IO.Directory.CreateDirectory(getPath(LibCommon.Constants.FolderTemp.EntityObject, true));
                //}
                if (!Directory.Exists(getPath(Constants.FolderTemp.Bootstrap_Admin, true)))
                {
                    System.IO.Directory.CreateDirectory(getPath(Constants.FolderTemp.Bootstrap_Admin, true));
                }
                //if (!Directory.Exists(getPath(LibCommon.Constants.FolderTemp.StoreProcedure, true)))
                //{
                //    System.IO.Directory.CreateDirectory(getPath(LibCommon.Constants.FolderTemp.StoreProcedure, true));
                //}
                if (!Directory.Exists(getPath(Constants.FolderTemp.Bootstrap_UserControl, true)))
                {
                    System.IO.Directory.CreateDirectory(getPath(Constants.FolderTemp.Bootstrap_UserControl, true));
                }
                #endregion


                #region "Copy file"
                foreach (var file in Directory.GetFiles(getPath(Constants.FolderTemp.App_Themes, false)))
                {
                    File.Copy(file, Path.Combine(getPath(Constants.FolderTemp.App_Themes, true), Path.GetFileName(file)), true);
                }
                foreach (var file in Directory.GetFiles(getPath(Constants.FolderTemp.DLL, false)))
                {
                    File.Copy(file, Path.Combine(getPath(Constants.FolderTemp.DLL, true), Path.GetFileName(file)), true);
                }
                foreach (var file in Directory.GetFiles(getPath(Constants.FolderTemp.Fonts, false)))
                {
                    File.Copy(file, Path.Combine(getPath(Constants.FolderTemp.Fonts, true), Path.GetFileName(file)), true);
                }
                //foreach (var file in Directory.GetFiles(getPath(LibCommon.Constants.FolderTemp.DataAccessObject, false)))
                //{
                //    File.Copy(file, Path.Combine(getPath(LibCommon.Constants.FolderTemp.DataAccessObject, true), Path.GetFileName(file)), true);
                //}
                foreach (var file in Directory.GetFiles(getPath(Constants.FolderTemp.PublicInterface, false)))
                {
                    File.Copy(file, Path.Combine(getPath(Constants.FolderTemp.PublicInterface, true), Path.GetFileName(file)), true);
                }
                foreach (var file in Directory.GetFiles(getPath(Constants.FolderTemp.Scripts, false)))
                {
                    File.Copy(file, Path.Combine(getPath(Constants.FolderTemp.Scripts, true), Path.GetFileName(file)), true);
                }
                //foreach (var file in Directory.GetFiles(getPath(LibCommon.Constants.FolderTemp.SharedLibraries, false)))
                //{
                //    File.Copy(file, Path.Combine(getPath(LibCommon.Constants.FolderTemp.SharedLibraries, true), Path.GetFileName(file)), true);
                //}
                //foreach (var file in Directory.GetFiles(getPath(LibCommon.Constants.FolderTemp.Images, false)))
                //{
                //    File.Copy(file, Path.Combine(getPath(LibCommon.Constants.FolderTemp.Images, true), Path.GetFileName(file)), true);
                //}
                foreach (var file in Directory.GetFiles(getPath(Constants.FolderTemp.Bootstrap_Admin, false)))
                {
                    File.Copy(file, Path.Combine(getPath(Constants.FolderTemp.Bootstrap_Admin, true), Path.GetFileName(file)), true);
                }
                foreach (var file in Directory.GetFiles(getPath(Constants.FolderTemp.Bootstrap_UserControl, false)))
                {
                    File.Copy(file, Path.Combine(getPath(Constants.FolderTemp.Bootstrap_UserControl, true), Path.GetFileName(file)), true);
                }
                //File.Copy(root + LibCommon.Constants.FolderTemp.Template + "\\" + LibCommon.FileTemp.Utilities_cs, root + LibCommon.Information.Author + "\\" + LibCommon.Constants.FolderTemp.SharedLibraries + "\\" + LibCommon.FileTemp.Utilities_cs, true);
                #endregion
                lblMsg.Text = "Copy file success!";
                lblMsg.ForeColor = System.Drawing.Color.Blue;
            }
            catch (Exception ex)
            {
                lblMsg.Text = ex.Message;
                lblMsg.ForeColor = System.Drawing.Color.Red;
            }
        }

        private void btnBootstrap_Click(object sender, EventArgs e)
        {
            lblMsg.Text = "";
            try
            {
                if (lstbField.Items.Count > 0 && lstbField.SelectedIndex != -1)
                {
                    string tblName = lstbField.SelectedItem.ToString();
                    if (tblName.PadRight(3, ' ').Contains("tbl"))
                    {
                        tblName = tblName.Substring(3);
                    }
                    LibCommon.DataAccessObjectEx = " _" + tblName + "DAO";
                    LibCommon.DataAccessObject = " " + tblName + "DAO";
                    LibCommon._EntityObject = " _" + tblName + "EO";
                    LibCommon.EntityObject = " " + tblName + "EO";
                    LibCommon.objEntityObject = " obj" + tblName + "EO";
                    LibCommon.UI = tblName + "UI";
                    LibCommon._DetailUC = tblName + "_DetailUC";
                    LibCommon._DetailUC1 = tblName + "_DetailUC1";
                    LibCommon._ListUC = tblName + "_ListUC";
                    LibCommon._ListUC1 = tblName + "_ListUC1";
                    LibCommon._NewUC = tblName + "_NewUC";

                    LibCommon.isAddOK = false;

                    LibCommon.fncBootstrapAspx(columnName, tblName);
                    LibCommon.fncBootstrapAspxCs(columnName, tblName);
                    LibCommon.fncBootstrapAspxDesignerCs(columnName, tblName);

                    LibCommon.fncBootstrapAscx_List(columnName, tblName);
                    LibCommon.fncBootstrapAscxCs_List(columnName, tblName);
                    LibCommon.fncBootstrapAscxDesignerCs_List(columnName, tblName);

                    LibCommon.fncBootstrapAscx_Detail(columnName, tblName);
                    LibCommon.fncBootstrapAscxCs_Detail(columnName, tblName);
                    LibCommon.fncBootstrapAscxDesignerCs_Detail(columnName, tblName);
                }
                lblMsg.Text = "Generate code success!!";
                lblMsg.ForeColor = System.Drawing.Color.Blue;
            }
            catch (Exception ex)
            {
                lblMsg.Text = ex.Message;
                lblMsg.ForeColor = System.Drawing.Color.Red;
            }
        }

        private void btnAll_Click(object sender, EventArgs e)
        {
            lblMsg.Text = "";
            try
            {
                CopyLib();
                string tblName = "";
                for (int i = 0; i < tableName.Count; i++)
                {
                    tblName = tableName[i];
                    LibCommon.tblFullName = tblName;
                    if (tblName.PadRight(3, ' ').Contains("tbl"))
                    {
                        tblName = tblName.Substring(3);
                    }
                    getColumn(tableName[i]);

                    LibCommon.DataAccessObjectEx = " _" + tblName + "DAO";
                    LibCommon.DataAccessObject = " " + tblName + "DAO";
                    LibCommon._EntityObject = " _" + tblName + "EO";
                    LibCommon.EntityObject = " " + tblName + "EO";
                    LibCommon.objEntityObject = " obj" + tblName + "EO";
                    LibCommon.UI = tblName + "UI";
                    LibCommon._DetailUC = tblName + "_DetailUC";
                    LibCommon._DetailUC1 = tblName + "_DetailUC1";
                    LibCommon._ListUC = tblName + "_ListUC";
                    LibCommon._ListUC1 = tblName + "_ListUC1";
                    LibCommon._NewUC = tblName + "_NewUC";
                    LibCommon.isAddOK = false;

                    LibCommon.fncBootstrapAspx(columnName, tblName);
                    LibCommon.fncBootstrapAspxCs(columnName, tblName);
                    LibCommon.fncBootstrapAspxDesignerCs(columnName, tblName);

                    LibCommon.fncBootstrapAscx_List(columnName, tblName);
                    LibCommon.fncBootstrapAscxCs_List(columnName, tblName);
                    LibCommon.fncBootstrapAscxDesignerCs_List(columnName, tblName);

                    LibCommon.fncBootstrapAscx_Detail(columnName, tblName);
                    LibCommon.fncBootstrapAscxCs_Detail(columnName, tblName);
                    LibCommon.fncBootstrapAscxDesignerCs_Detail(columnName, tblName);

                    LibCommon.fncStoreProcedure(columnName, tblName);
                    LibCommon.fncDataAccessObject(columnName, tblName);
                    LibCommon.fncEntityObject_New(columnName, tblName);
                }
                LibCommon.fncAdminMaster(tableName);
                LibCommon.fncAdminMasterCs(columnName, tblName);
                LibCommon.fncAdminMasterDesignerCs(columnName, tblName);
                lblMsg.Text = "Generate code success!!";
                lblMsg.ForeColor = System.Drawing.Color.Blue;
            }
            catch (Exception ex)
            {
                lblMsg.Text = ex.Message;
                lblMsg.ForeColor = System.Drawing.Color.Red;
            }
        }

        private void btnEO_New_Click(object sender, EventArgs e)
        {
            lblMsg.Text = "";
            try
            {
                String tblName = LoadConfig();
                if (!String.IsNullOrEmpty(tblName))
                {
                    LibCommon.fncEntityObject_New(columnName, tblName);
                    lblMsg.Text = "Generate code success!";
                    lblMsg.ForeColor = System.Drawing.Color.Blue;
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = ex.Message;
                lblMsg.ForeColor = System.Drawing.Color.Red;
            }
        }

        private void btnNewUC_Click(object sender, EventArgs e)
        {
            lblMsg.Text = "";
            try
            {
                String tblName = LoadConfig();
                if (!String.IsNullOrEmpty(tblName))
                {
                    LibCommon.fncBootstrapAscx_All_New(columnName, tblName);
                    LibCommon.fncBootstrapAscxCs_All_New(columnName, tblName);
                    LibCommon.fncBootstrapAscxDesignerCs_All_New(columnName, tblName);

                    LibCommon.fncBootstrapAscx_Single_New(columnName, tblName);
                    LibCommon.fncBootstrapAscxCs_Single_New(columnName, tblName);
                    LibCommon.fncBootstrapAscxDesignerCs_Single_New(columnName, tblName);

                    lblMsg.Text = "Generate code success!";
                    lblMsg.ForeColor = System.Drawing.Color.Blue;
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = ex.Message;
                lblMsg.ForeColor = System.Drawing.Color.Red;
            }

        }

        public String LoadConfig()
        {
            String tblName = "";
            if (lstbField.Items.Count > 0 && lstbField.SelectedIndex != -1)
            {
                LibCommon.tblFullName = lstbField.SelectedItem.ToString();
                tblName = lstbField.SelectedItem.ToString();
                if (tblName.PadRight(3, ' ').Contains("tbl"))
                {
                    tblName = tblName.Substring(3);
                }
                LibCommon.DataAccessObject = tblName + "DAO";
                LibCommon.DataAccessObjectEx = " " + tblName + "DAO";

                LibCommon._EntityObject = "_" + tblName + "EO";
                LibCommon._EntityObjectEx = " _" + tblName + "EO";
                LibCommon._EntityObjectExx = " _" + tblName + "EO ";

                LibCommon.EntityObject = tblName + "EO";
                LibCommon.EntityObjectEx = " " + tblName + "EO";
                LibCommon.EntityObjectExx = " " + tblName + "EO ";

                LibCommon.objEntityObject = "obj" + tblName + "EO";
                LibCommon.objEntityObjectEx = " obj" + tblName + "EO";

                LibCommon.UI = tblName + "UI";
                LibCommon._DetailUC = tblName + "_DetailUC";
                LibCommon._DetailUC1 = tblName + "_DetailUC1";
                LibCommon._ListUC = tblName + "_ListUC";
                LibCommon._ListUC1 = tblName + "_ListUC1";
                LibCommon._NewUC = tblName + "_NewUC";
                LibCommon._NewExUC = tblName + "_NewExUC";

                LibCommon.isAddOK = false;

                //foreach (ColumnEO item in columnName)
                //{
                //    (new ColumnDAO()).InsertItem(item);
                //}
                LibCommon.isTableAttack = chkSEO.Checked;
                if (chkSEO.Checked)
                {
                    List<ColumnEO> lst = (new ColumnDAO()).SelectList();
                    foreach (var item in lst)
                    {
                        item.bTableAttack = true;
                    }
                    columnName.AddRange(lst);
                    columnName = columnName.GroupBy(elem => elem.sColumnName).Select(group => group.First()).ToList();
                }
            }
            else
            {
                lblMsg.Text = "Chưa chọn bảng";
                lblMsg.ForeColor = System.Drawing.Color.Red;
            }
            return tblName;
        }

        //        private void btnGenVariable_Click(object sender, EventArgs e)
        //        {
        //            List<string> allcol = new List<string>();
        //            for (int i = 0; i < listBox1.Items.Count; i++)
        //            {
        //                string curtable = listBox1.Items[i].ToString();
        //                string Query =
        //                           @"SELECT [Column_NAME]
        //                           FROM INFORMATION_SCHEMA.Columns
        //                           WHERE Table_Name='" + curtable + "'";
        //                var con = new SqlConnection("Data Source=" + txtServer.Text + ";Initial Catalog=" + cmbDatabase.Text + ";Integrated Security=True;");
        //                var cmd = new SqlCommand(Query, con);
        //                SqlDataReader reader;
        //                try
        //                {
        //                    con.Open();
        //                    reader = cmd.ExecuteReader();
        //                    while (reader.Read())
        //                    {
        //                        allcol.Add(reader[0].ToString());
        //                    }
        //                }
        //                catch (SqlException ex)
        //                {
        //                    MessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //                }
        //            }
        //            //frm_Gen_Fielnames f = new frm_Gen_Fielnames(allcol);
        //            //f.ShowDialog();
        //        }
    }
}
